import { EventBus } from '../EventBus';
import { Scene } from 'phaser';
import { webSocketManager } from '../WebSocketManager';

export class GameOver extends Scene
{
    constructor ()
    {
        super('GameOver');
    }

    create (data)
    {
        this.cameras.main.setBackgroundColor(0xff0000);

        this.add.image(512, 384, 'background').setAlpha(0.5);

        // 获取游戏结束信息
        const finalScore = data?.finalScore || 0;
        const reason = data?.reason || '游戏结束';
        const winner = data?.winner || '';

        this.add.text(512, 300, 'Game Over', {
            fontFamily: 'Arial Black', fontSize: 64, color: '#ffffff',
            stroke: '#000000', strokeThickness: 8,
            align: 'center'
        }).setOrigin(0.5).setDepth(100);

        // 显示最终分数
        this.add.text(512, 380, `最终分数: ${finalScore}`, {
            fontFamily: 'Arial', fontSize: 32, color: '#ffff00',
            stroke: '#000000', strokeThickness: 4,
            align: 'center'
        }).setOrigin(0.5).setDepth(100);

        // 显示游戏结束原因
        this.add.text(512, 420, reason, {
            fontFamily: 'Arial', fontSize: 24, color: '#ffcccc',
            stroke: '#000000', strokeThickness: 3,
            align: 'center'
        }).setOrigin(0.5).setDepth(100);

        // 如果有获胜者，显示获胜者信息
        if (winner) {
            this.add.text(512, 460, `获胜者: ${winner}`, {
                fontFamily: 'Arial', fontSize: 28, color: '#00ff00',
                stroke: '#000000', strokeThickness: 4,
                align: 'center'
            }).setOrigin(0.5).setDepth(100);
        }

        // 添加点击返回主菜单的提示
        this.add.text(512, 520, 'Click to return to Main Menu', {
            fontFamily: 'Arial', fontSize: 24, color: '#ffffff',
            stroke: '#000000', strokeThickness: 4,
            align: 'center'
        }).setOrigin(0.5).setDepth(100);

        // 添加点击事件监听器
        this.input.on('pointerdown', () => {
            this.changeScene();
        });

        EventBus.emit('current-scene-ready', this);
    }

    changeScene ()
    {
        // 发送返回主菜单消息
        webSocketManager.sendMessage({
            type: 'return_to_menu',
            data: {
                timestamp: Date.now()
            }
        });
        
        this.scene.start('MainMenu');
    }
}
